//
//  PackageListVC.m
//  ZhiBoYuan
//
//  Created by JW on 2018/4/26.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "PackageListVC.h"

#import "PackageListModel.h"
#import "MicroCourseModel.h"

#import "ABCell.h"

#import "AdetailViewController.h"

#import "ChongZhiViewController.h"

static NSString * identB = @"ABCell";

@interface PackageListVC ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;


@property (nonatomic,strong)UIButton *buttonA;
@property (nonatomic,strong)UIButton *buttonB;
@property (nonatomic, assign)BOOL xuedouIsGou;
@property (nonatomic, assign)long totalDou;
@end

@implementation PackageListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initWithViews];
    
    [self downloadPackageListDatas];

}

- (void)downloadPackageListDatas{
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       @"package_id":self.package_id// 1 直播 2微课 3套餐
                       };
    [SGHttpTool POST:Host_Append(PackageCourseList) parameter:parameter sucess:^(id responseObject) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString *resultStr =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        ZYLog(@"%@",resultStr);
        
        if ([[responseObject[@"data"] valueForKey:@"had_collect"]intValue] == 1) {
            [_buttonA setTitle:@"取消收藏" forState:0];
        }else{
            [_buttonA setTitle:@"加入收藏" forState:0];
        }
        
        if (Teacher) {
                [_buttonB setTitle:@"进入学习" forState:0];

        }else{
            if ([[responseObject[@"data"] valueForKey:@"had_buy"]intValue] == 1) {
                //已购买
                [_buttonB setTitle:@"进入学习" forState:0];
            }else{
                [_buttonB setTitle:@"加入学习" forState:0];
            }
            
        }
        
        
        SGReceive *receive = [SGReceive receiveWithResponseObject:responseObject dataClass:[PackageListModel class]];
        [self.dataArray addObject:receive.data];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}


#pragma mark -- UITableViewDataSource,UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [UIView new];
    headerView.backgroundColor = [UIColor whiteColor];
    headerView.size = CGSizeMake(ScreenWidth, 49);
    
    UILabel *videoNum = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth/2, 49)];
    [headerView addSubview:videoNum];
    
    UILabel *totalPrice = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/2, 0, ScreenWidth/2, 49)];
    totalPrice.textAlignment = NSTextAlignmentRight;
    [headerView addSubview:totalPrice];
    PackageListModel *package = self.dataArray[section];
    videoNum.text = [NSString stringWithFormat:@" 该套餐共%ld个视频",package.total_count];
    totalPrice.text = [NSString stringWithFormat:@"共计: %ld学豆 ",package.total_price];
    
    _totalDou = package.total_price;
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 49, ScreenWidth, 1)];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [headerView addSubview:line];
    
    return headerView;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    PackageListModel *package = self.dataArray[section];
    return package.course_list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ABCell *cell = [tableView dequeueReusableCellWithIdentifier:identB forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    PackageListModel *package = self.dataArray[indexPath.section];
    cell.microModel = package.course_list[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    AdetailViewController *vc= [[AdetailViewController alloc]initWithNibName:@"AdetailViewController" bundle:nil];
//
//    PackageListModel *package = self.dataArray[indexPath.section];
//    MicroCourseModel *model = package.course_list[indexPath.row];
//    vc.course_id = model.microCourseID;
//    [self.navigationController pushViewController:vc animated:YES];
    
        PackageListModel *package = self.dataArray[indexPath.section];
        MicroCourseModel *model = package.course_list[indexPath.row];
    
    
     [Helper keChengDetailFromVC:self course_id:model.microCourseID];
    
}

#pragma mark - 视图
- (void)initWithViews{
    self.title = @"套餐课";
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.buttonA];
    CGFloat bot = 0;
    if (iPhoneX) { bot = 34; }
    _buttonA.sd_layout
    .leftSpaceToView(self.view, 0)
    .bottomSpaceToView(self.view, bot)
    .widthIs(ScreenWidth/2)
    .heightIs(50);
    
    
    [self.view addSubview:self.buttonB];
    _buttonB.sd_layout
    .rightSpaceToView(self.view, 0)
    .bottomSpaceToView(self.view, bot)
    .widthIs(ScreenWidth/2)
    .heightIs(50);
    
    
}

#pragma makr -- property
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}




- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *  tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT -TAB_BAR_HEIGHT) style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.delegate        = self;
        tableView.dataSource      = self;
        //        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
        
        tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
        
        //        self.extendedLayoutIncludesOpaqueBars = YES;
        
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        tableView.scrollIndicatorInsets = _tableView.contentInset;
        
        [tableView registerNib:[UINib nibWithNibName:identB bundle:nil] forCellReuseIdentifier:identB];
        
        [tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        __weak __typeof(&*self)weakSelf = self;
        
        // 下拉刷新
        //        tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //
        //            weakSelf.pageIndex = 1;
        //
        //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //                [weakSelf.tableView.mj_header endRefreshing];
        //            });
        //        }];
        //
        //        // 上拉加载
        //        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //
        //            if ( weakSelf.pageIndex < -1 ) {  weakSelf.pageIndex = 1;  }
        //
        //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //                [weakSelf.tableView.mj_footer endRefreshing];
        //            });
        //        }];
        _tableView = tableView;
        
    }
    return _tableView;
}

-(UIButton *)buttonA{
    if (!_buttonA) {
        _buttonA = [UIButton buttonWithType:(UIButtonTypeCustom)];
        
        [_buttonA setBackgroundColor:[UIColor whiteColor]  ];
        
        [_buttonA setTitle:@"加入收藏" forState:0];
        
        [_buttonA addTarget:self action:@selector(shoucangAction) forControlEvents:(UIControlEventTouchUpInside)];
        
        [_buttonA setTitleColor:ZhuTiColor forState:(UIControlStateNormal)];
        
        _buttonA.layer.borderColor = ZhuTiColor.CGColor;
        
        _buttonA.layer.borderWidth = 1;
        
    }
    return _buttonA;
}

-(void)shoucangAction{
    
    if ([_buttonA.titleLabel.text isEqualToString:@"加入收藏"]) {
        SGParameter *parameter  = [[SGParameter alloc] init];
        parameter.body = @{
                           @"course_id":self.package_id// 1 直播 2微课 3套餐
                           };
        
        [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Collect&a=addCourse",HTTPP] parameter:parameter sucess:^(id responseObject) {
            NSLog(@"%@",responseObject);
            
            NSDictionary *dic = responseObject;
            
            if ([dic[@"status"] intValue] == 200) {
                
                [_buttonA setTitle:@"取消收藏" forState:0];
                
                [MBProgressHUD showTextOnly:self.view message:@"收藏成功" delay:2.0f];
                
            }else{
                [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            
        }];
    }else{
        
        //取消收藏
        SGParameter *parameter  = [[SGParameter alloc] init];
        parameter.body = @{@"course_id":self.package_id,
                           };
        
        [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Collect&a=delCourse",HTTPP] parameter:parameter sucess:^(id responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary *dic = responseObject;
            
            if ([dic[@"status"] intValue] == 200) {
                [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
                
                [_buttonA setTitle:@"加入收藏" forState:0];
                
            }else{
                [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            
        }];
        
    }

}

-(UIButton *)buttonB{
    if (!_buttonB) {
        _buttonB = [UIButton buttonWithType:(UIButtonTypeCustom)];
        
        [_buttonB setBackgroundColor:ZhuTiColor];
        [_buttonB setTitle:@"加入学习" forState:0];
        
        [_buttonB addTarget:self action:@selector(addToStudyAction) forControlEvents:(UIControlEventTouchUpInside)];

        
    }
    return _buttonB;
}

//加入学习
-(void)addToStudyAction{

    if (Teacher) {
        //学习
        PackageListModel *package = self.dataArray[0];
        MicroCourseModel *model = package.course_list[0];
        
        [Helper keChengDetailFromVC:self course_id:model.microCourseID];
    }else{
        
        if ([_buttonB.titleLabel.text isEqualToString:@"加入学习"]) {
         
            NSString *totalDou = [ZYUserManager userInfo].left_xuedou;
            
            
            if (_totalDou == 0) {
                SGParameter *parameter  = [[SGParameter alloc] init];
                parameter.body = @{
                                   @"course_id":self.package_id// 1 直播 2微课 3套餐
                                   };
                
                [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Order&a=buyCourse",HTTPP] parameter:parameter sucess:^(id responseObject) {
                    NSLog(@"%@",responseObject);
                    
                    NSDictionary *dic = responseObject;
                    
                    if ([dic[@"status"] intValue] == 200) {
                        if ([dic[@"data"][@"status"] intValue] == 1) {
                            
                            [_buttonB setTitle:@"进入学习" forState:0];
                            
                            [MBProgressHUD showTextOnly:self.view message:@"加入成功" delay:2.0f];
                        }else{
                            [MBProgressHUD showTextOnly:self.view message:dic[@"data"][@"msg"] delay:2.0f];
                            
                        }
                        
                        
                    }else{
                        [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
                    }
                    
                } failure:^(NSError *error) {
                    NSLog(@"%@",error);
                    
                }];
            }else{
                
                NSString *message1 = [NSString stringWithFormat:@"您确定使用%ld个学豆？",_totalDou];
                
                if ([totalDou longValue] >= _totalDou) {
                    _xuedouIsGou = YES;
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:message1 delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil, nil];
                    [alertView show];
                }else{
                    _xuedouIsGou = NO;
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"您的学豆不足，是否去充值？" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil, nil];
                    [alertView show];
                }
            }
           
            
        }else{
            //学习
            PackageListModel *package = self.dataArray[0];
            MicroCourseModel *model = package.course_list[0];
            
            [Helper keChengDetailFromVC:self course_id:model.microCourseID];
            
        }
        
    }
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
    }else if (buttonIndex == 1){
        
        if (_xuedouIsGou == YES) {
            
            SGParameter *parameter  = [[SGParameter alloc] init];
            parameter.body = @{
                               @"course_id":self.package_id// 1 直播 2微课 3套餐
                               };
            
            [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Order&a=buyCourse",HTTPP] parameter:parameter sucess:^(id responseObject) {
                NSLog(@"%@",responseObject);
                
                NSDictionary *dic = responseObject;
                
                if ([dic[@"status"] intValue] == 200) {
                    if ([dic[@"data"][@"status"] intValue] == 1) {
                        
                        [_buttonB setTitle:@"进入学习" forState:0];
                        
                        [MBProgressHUD showTextOnly:self.view message:@"加入成功" delay:2.0f];
                    }else{
                        [MBProgressHUD showTextOnly:self.view message:dic[@"data"][@"msg"] delay:2.0f];
                        
                    }
                    
                    
                }else{
                    [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
                }
                
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                
            }];
        }else{
            ChongZhiViewController *chongVC = [[ChongZhiViewController alloc]init];
            [self.navigationController pushViewController:chongVC animated:YES];
            
        }
        
    }
    
}


@end
